#include "myinet.h"
#include "tools.h"
#include <time.h>

#define BUFF_SIZE (1024*1024)

/*** 提供当前日期时间的服务 ***/

/**
 * both the address and the port should be in network byte order
 */
static void 
here_is_your_time_(int socket_fd, const struct sockaddr_in * addr,
        socklen_t addrlen){

    // get timestamp using time()
    time_t cur = time(NULL);
    // write time string to socket_fd
    if (sendto(socket_fd, (char*)&cur, sizeof(time_t), 0,
                (const struct sockaddr*)addr, addrlen) < 0){
        error("error writing to client");
        perror("send");
        return;
    }
}

int main(int argc, char** argv){

    // should specify the address and port
    if (argc < 2){
        fprintf(stderr, "Usage: %s <port>\n", argv[0]);
        error_exit(NULL, "error parsing options");
    }


    // 创建socket
    int sfd;
    info("creating socket");
    if ( (sfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
        error_exit("socket", NULL);
    struct sockaddr_in addr;

    // 1M 缓存
    char buf[BUFF_SIZE] = {0};


    // 设置监听地址
    addr.sin_addr.s_addr = INADDR_ANY;
    addr.sin_family = AF_INET;

    short p = htons(atoi(argv[1]));
    addr.sin_port = p;

    info("binding port");
    // 绑定端口
    if (bind(sfd, (struct sockaddr*)&addr, sizeof(addr)) < 0){
        error_exit("bind", NULL);
    }

    struct sockaddr_in request_addr;
    int req_addr_len = sizeof(request_addr);

    info("listening...");
    // 循环接收请求
    for(;;){
        // 阻塞，直到有一个请求
        if (recvfrom(sfd, buf, sizeof(buf), 0,
                    (struct sockaddr*)&request_addr, &req_addr_len) < 0)
            error_exit("recvfrom", NULL);
        info("received request from %s:%d", inet_ntoa(request_addr.sin_addr),
                htons(request_addr.sin_port));

        here_is_your_time_(sfd, &request_addr, req_addr_len);
    }

    return 0;
}
